import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/get_zero_model_entity.dart';
import 'package:flutter_deer/database/beans/shift/current_shift_entity.dart';
import 'package:flutter_deer/database/beans/shift/turn_orver_bean.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/res/emuns/pay_type_enum.dart';
import 'package:flutter_deer/util/print/data/print_link_type.dart';
import 'package:flutter_deer/util/print/print_manager.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';

class TurnShiftProvider extends BaseNetProvider {
  String currentWorkCycleId = "";
  String currentWorkCycleName = "";
  int turnOverFrom = 0;
  GetZeroModelEntity? zeroModelEntity;
  CurrentShiftEntity? currentShift;
  final mPrinter = Get.find<PrintEngineManager>();

  // 点击交班
  void clickTurnOver([int from = 0]) {
    currentShift = CurrentShiftEntity.get();
    currentWorkCycleId = currentShift?.id ?? '';
    currentWorkCycleName = currentShift?.workCycleCode ?? '';

    zeroModelEntity = GetZeroModelEntity().get();
    turnOverFrom = from;

    if (zeroModelEntity?.type == 1) {
      // 1、是否1分钟内多次交班
      _whetherShiftAgainInMin((bool b, int count) {
        if (b) {
          // 2、是否有人交班
          _whetherHasTurnOvered((ConfirmHandOverBean? data) {
            // 3、零管的确认弹窗
            _showZeroPipeConfirmTime(data);
          });
        } else {
          _showMinDialog();
        }
      });
    } else {
      // 1、是否1分钟内多次交班
      _whetherShiftAgainInMin((bool can, int count) {
        if (can) {
          // 2、是否有人交班
          _whetherHasTurnOvered((ConfirmHandOverBean? data) {
            // 3、是否存在待支付订单
            if (count > 0) {
              _showExistUnPayOrder(count);
            } else {
              // 4、展示时间确认 取真的交班
              _confirmHandoverTime();
            }
          });
        } else {
          _showMinDialog();
        }
      });
    }
  }

  // 是否1分钟内多次交班
  void _whetherShiftAgainInMin(Function(bool, int) callback) {
    getShiftExistUnpaid((bool can, int count) {
      callback(can, count);
    }, (error) {
      _showHttpError(error);
    });
  }

  // 是否已经被班结过了
  void _whetherHasTurnOvered(void Function(ConfirmHandOverBean?) callback) {
    confirmHandoverTime((data) {
      if (data?.workCycleStatus == 1) {
        // 未交班
        callback(data);
      }
      if (data?.workCycleStatus == 2) {
        // 已交班
        _showHasTurnOver(data);
      }
    }, (error) {
      _showHttpError(error);
    });
  }

  // 一分钟内不可多次交班
  void _showMinDialog() {
    // 显示对话框: 一分钟内禁止多次交班，请稍候重试
    _showHttpError('一分钟内禁止多次交班，请稍候重试');
  }

  // 存在未结算订单
  void _showExistUnPayOrder(int count) {
    // 用户选择处理
    Get.dialog<void>(AlertDialog(
      title: const Text('交班'),
      content: Text('确认交班: 当前存在$count笔待支付订单，是否强制交班？', style: const TextStyle(color: Colors.redAccent, fontSize: 16)),
      actions: [
        TextButton(child: const Text('确认'), onPressed: () => Get.back<void>()),
        TextButton(child: const Text('取消'), onPressed: () => _confirmHandoverTime()),
      ],
    ));
  }

  // 确认时间
  void _confirmHandoverTime() {
    confirmHandoverTime((data) {
      if (data?.workCycleStatus == 1) {
        // 未交班
        _showConfirmTime(data);
      }
      if (data?.workCycleStatus == 2) {
        // 已交班
        _showHasTurnOver(data);
      }
    }, (error) {
      _showHttpError(error);
    });
  }

  // 零管默认的 确认时间弹窗
  void _showZeroPipeConfirmTime(ConfirmHandOverBean? data) {
    Widget handleType = PressBlueButton(width: 60, text: '交班', onPressed: () => Get.back<void>());
    if (data?.energyOrderPayingIds.isEmpty == true && data?.energyOrderIds.isEmpty == true) {
      handleType = PressBlueButton(width: 60, text: '交班', onPressed: () => _realHandover());
    } else if (data?.energyOrderPayingIds.isNotEmpty == true) {
      handleType = PressBlueButton(width: 100, text: '解锁订单', onPressed: () => unlockOrders(data?.energyOrderIds));
    } else if (data?.energyOrderIds.isNotEmpty == true) {
      handleType = PressBlueButton(width: 120, text: '自动核销并交班', onPressed: () => _showAutoConfirm(data?.energyOrderIds));
    }
    Get.dialog<void>(AlertDialog(
      title: const Text('交班'),
      content: SizedBox(
        width: 250,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('''
班次号：${data?.workCycleCode ?? ''} 
开始时间：${data?.startTime ?? ''}      
油品实际销量（升）：${data?.energyOrderGoodsQuantity ?? 0}      
应收金额（元）：${data?.receivableAmount ?? 0}      
优惠金额（元）：${data?.discountAmount ?? 0}      
实收金额（元）：${data?.actualAmount ?? 0}      
线上收款（元）：${data?.onlinePaymentAmount ?? 0}      
订单笔数：${data?.orderCount ?? 0} 
    ''', style: const TextStyle(color: Colors.black, fontSize: 16)),
            RichText(
              text: TextSpan(
                style: const TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  if (data?.energyOrderIds.isNotEmpty ?? false) TextSpan(text: '未核销订单：${data?.energyOrderIds.length ?? 0}笔 \n', style: const TextStyle(color: Colors.red)),
                  if (data?.energyOrderPayingIds.isNotEmpty ?? false)
                    TextSpan(text: '已锁定订单：${data?.energyOrderPayingIds.length ?? 0}笔 \n', style: const TextStyle(color: Colors.red)),
                ],
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(child: const Text('取消'), onPressed: () => Get.back<void>()),
        handleType,
      ],
    ));
  }

  // 自动核销
  void _showAutoConfirm(List<String>? energyOrderIds) {
    checkPatchPayDataVm(energyOrderIds, (result) {
      // 显示自动核销对话框
      // print("自动核销并班结: 本次需要核销：$result元");
      Get.dialog<void>(AlertDialog(
        title: const Text('自动核销并班结'),
        content: Text('本次需要核销：$result元\n共计：${energyOrderIds?.length ?? 0}笔订单\n默认支付方式：现金', style: const TextStyle(color: Colors.black, fontSize: 16)),
        actions: [
          TextButton(child: const Text('取消'), onPressed: () => Get.back<void>()),
          TextButton(child: const Text('确认'), onPressed: () {
            // 批量核销 并班结
            patchPay(PostPatchPay(energyOrderIds ?? []));
            Get.back<void>();
          }),
        ],
      ));
    }, (error) {
      _showHttpError(error);
    });
  }

  // 批量核销
  void patchPay(PostPatchPay bean) {
    // 批量核销 之前再次验证是否存在 锁定订单
    confirmHandoverTime((data) {
      if (data?.energyOrderPayingIds.isEmpty ?? true) {
        patchPayVmMq(bean, () {
          realHandOverApi(true);
        });
      } else {
        clickTurnOver();
        Toast.show('当前存在${data?.energyOrderPayingIds.length ?? 0}笔锁定订单，请先解锁！');
      }
    }, (error) {
      _showHttpError(error);
    });
  }

  // 确认交班
  void _showConfirmTime(ConfirmHandOverBean? data) {
    Get.dialog<void>(AlertDialog(
      title: const Text('确认交班'),
      content: Text('''
        班次：${data?.workCycleCode}
        接班：${data?.startTime}
        交班：${data?.nowDateTime}
        本班实收金额：${data?.actualAmount}元
      ''', style: const TextStyle(color: Colors.black, fontSize: 16)),
      actions: [
        TextButton(child: const Text('取消'), onPressed: () => Get.back<void>()),
        TextButton(child: const Text('确认'), onPressed: () => realHandOverApi()),
      ],
    ));
  }

  // 已经被别人交班了
  void _showHasTurnOver(ConfirmHandOverBean? data) {
    // 显示交班重复对话框
    _showHttpError('''
      交班重复！
      [${data?.workCycleCode}]班次已经被[${data?.headUserName}]交班
      当前进行中的班次为[${data?.newWorkCycleCode}]
    ''');
  }

  // 真正的交班
  void _realHandover() {
    Get.dialog<void>(AlertDialog(
      title: const Text('警告！'),
      content: const Text('为了避免数据丢失，\n请勿加油中进行交班！', style: TextStyle(color: Colors.redAccent, fontSize: 16)),
      actions: [
        TextButton(child: const Text('取消'), onPressed: () => Get.back<void>()),
        TextButton(child: const Text('继续'), onPressed: () {
          Get.back<void>();
          realHandOverApi();
        }),
      ],
    ));
  }

  /// 交班接口
  void realHandOverApi([bool printLater = false]) {
    asyncRequestNetwork<HandOverBean>(
      Method.get,
      url: HttpApi.confirmHandover.replaceAll('workCycleId', currentWorkCycleId),
      onSuccess: (data) {
        // 保存当前班次
        data?.newMwc?.save();
        if (printLater) {
          Toast.show('批量核销中，班结小票稍后打印');
        } else {
          // 处理成功数据
          printShift(currentWorkCycleId, (data) {
            if (data != null) {
              print('班结打印成功');
              mPrinter.printShift(data, PrintLinkType.WORK_CLASS_KNOT_TICKET_CONFIG);
            }
          });
        }
      },
      onError: (code, msg) {
        // 处理错误数据
        _showHttpError(msg);
      },
    );
  }

  // http错误提示
  void _showHttpError(dynamic error, [String title = '系统提示']) {
    Get.dialog<void>(AlertDialog(
      title: Text(title),
      content: Text(error.toString(), style: const TextStyle(color: Colors.redAccent, fontSize: 16)),
      actions: [TextButton(child: const Text('确认'), onPressed: () => Get.back<void>())],
    ));
  }

  // 解锁并交班
  void unlockOrders(List<String>? energyOrderIds) {
    asyncRequestNetwork<dynamic>(
      Method.post,
      url: HttpApi.unlockBatch,
      params: {
        'energyOrderIds': energyOrderIds,
      },
      onSuccess: (data) {
        Toast.show('解锁成功');
        clickTurnOver();
      },
      onError: (code, msg) {
        _showHttpError(msg);
      },
    );
  }

  // 刷新数据 班结成功了
  void turnOverSuccessRefresh() {
    // 刷新界面数据
  }

  void getShiftExistUnpaid(void Function(bool, int) onSuccess, void Function(String) onFail) {
    asyncRequestNetwork<Map<String, dynamic>>(
      Method.get,
      url: HttpApi.existUnpaid.replaceAll('workCycleId', currentWorkCycleId),
      onSuccess: (data) {
        final orderCount = int.tryParse('${data?['orderCount']}') ?? 0;
        onSuccess(data?['bool'] == true, orderCount);
      },
      onError: (code, msg) {
        onFail(msg);
      },
    );
  }

  void confirmHandoverTime(void Function(ConfirmHandOverBean?) onSuccess, void Function(String) onFail) {
    // 实现网络请求
    asyncRequestNetwork<ConfirmHandOverBean>(
      Method.get,
      url: HttpApi.confirmHandoverTime.replaceAll('workCycleId', currentWorkCycleId),
      onSuccess: (data) {
        // 处理成功数据
        onSuccess(data);
      },
      onError: (code, msg) {
        // 处理错误数据
        onFail(msg);
      },
    );
  }

  void checkPatchPayDataVm(List<String>? energyOrderIds, void Function(String) onSuccess, void Function(String) onFail) {
    asyncRequestNetwork<String>(
      Method.post,
      url: HttpApi.verificationVerify,
      params: {
        'energyOrderIds': energyOrderIds,
      },
      onSuccess: (data) {
        onSuccess('$data');
      },
      onError: (code, msg) {
        onFail(msg);
      },
    );
  }

  void patchPayVmMq(PostPatchPay bean, void Function()? onSuccess) {
    asyncRequestNetwork<dynamic>(
      Method.post,
      url: HttpApi.verificationMq,
      params: {
        'energyOrderIds': bean.energyOrderIds,
        'payMethod': bean.payMethod,
        'payType': bean.payType,
      },
      onSuccess: (data) {
        onSuccess?.call();
        print("批量核销Mq: $data");
      },
      onError: (code, msg) {
        _showHttpError(msg);
      },
    );
  }

  /// 班结打印
  void printShift(String workCycleId, void Function(Map<String, dynamic>?) onSuccess) {
    asyncRequestNetwork<Map<String, dynamic>>(
      Method.get,
      url: HttpApi.printShift.replaceAll('workCycleId', workCycleId),
      onSuccess: (data) {
        print("班结打印: $data");
        onSuccess.call(data);
      },
      onError: (code, msg) {
        print("班结打印失败: $msg");
      },
    );
  }
}

class PostPatchPay {
  PostPatchPay(this.energyOrderIds);

  List<String> energyOrderIds = [];
  String? payMethod = PayTypeEnum.Cash.paymentCode;
  String? payType = PayTypeEnum.Cash.paymentCode;
}
